package edu.tgc.web.controller.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashSet;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.abyss.common.web.controller.easyui.CommonCrudEasyUiController;
import org.abyss.common.web.controller.easyui.EasyuiAjaxFormResult;
import org.abyss.common.web.controller.easyui.EasyuiResultBuilder;
import org.abyss.data.specifications.Rule;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.tgc.entity.file.TbData;
import edu.tgc.entity.system.SysUser;
import edu.tgc.security.SessionUserUtils;
import edu.tgc.service.system.SysUserService;
import edu.tgc.web.form.file.DataForm;
@Controller
@RequestMapping(value="file/data")
public class DataController extends CommonCrudEasyUiController<TbData, UUID, DataForm>{
	@Autowired
	private SysUserService userService;

	@Override
	public Specification<TbData> buildSearch(DataForm form) {
		HashSet<Rule> rules=new HashSet<>();
		UUID id = SessionUserUtils.getSysUser().getId();
		SysUser user=userService.getById(id);
		rules.add(Rule.property("user").equal(user));
		return Rule.and(rules).toSpecification();
	}

	@RequestMapping(value="/create1",method=RequestMethod.POST)
	@ResponseBody
	public EasyuiAjaxFormResult create(MultipartFile uploadFile, DataForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		//MultipartFile uploadFile = form.getUploadFile();
		if(uploadFile!=null){
			try {
				String filename = uploadFile.getOriginalFilename();
				File file=new File(filename);
				filename=file.getName();
				form.setFilename(filename);
				//String path = TbData.getPath();
				File path =new File(TbData.getPath());
				if(!path.isDirectory()){
					path.mkdirs();
				}
				form.setCreateTime(new Date());
				form.setUser(SessionUserUtils.getSysUser());
				TbData data=new TbData();
				BeanUtils.copyProperties(form, data, "uploadFile");
				data = baseService.saveAndFlush(data);
				File outFile =new File(path, data.getId().toString());
				uploadFile.transferTo(outFile);
				return EasyuiResultBuilder.buildAjaxResult("新增记录成功");
			} catch (Exception e) {
				return EasyuiResultBuilder.buildAjaxResultError("新增记录失败");
			} 
		}else{
			form.setUser(SessionUserUtils.getSysUser());
			return super.create(form, bindingResult, model, redirectAttributes);
		}
		
	}
	
	@RequestMapping(value="/update1",method=RequestMethod.POST)
	@ResponseBody
	public EasyuiAjaxFormResult update(MultipartFile uploadFile, DataForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		if(uploadFile!=null){
			try {
				String filename = uploadFile.getOriginalFilename();
				File file=new File(filename);
				filename=file.getName();
				form.setFilename(filename);
				//String path = TbData.getPath();
				File path =new File(TbData.getPath());
				if(!path.isDirectory()){
					path.mkdirs();
				}
				form.setCreateTime(new Date());
				form.setUser(SessionUserUtils.getSysUser());
				TbData data=baseService.getById(form.getId());
				BeanUtils.copyProperties(form, data, "uploadFile");
				data = baseService.saveAndFlush(data);
				File outFile =new File(path, data.getId().toString());
				uploadFile.transferTo(outFile);
				return EasyuiResultBuilder.buildAjaxResult("修改记录成功");
			} catch (Exception e) {
				return EasyuiResultBuilder.buildAjaxResultError("修改记录失败");
			} 
		}else{
			form.setUser(SessionUserUtils.getSysUser());
			form.setFilename(baseService.getById(form.getId()).getFilename());
			return super.update(form, bindingResult, model, redirectAttributes);
		}
	}

	@Override
	public EasyuiAjaxFormResult delete(DataForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		TbData data=baseService.getById(form.getId());
		File file=new File(TbData.getPath(),data.getId().toString());
		if(file.exists()){
			file.delete();
		}
		return super.delete(form, bindingResult, model, redirectAttributes);
	}
	
	@RequestMapping(value="/download")
	@ResponseBody
	public Object download(String id,HttpServletRequest request,HttpServletResponse response) throws IOException{
		TbData data=baseService.getById(UUID.fromString(id));
		File file=new File(TbData.getPath(),data.getId().toString());
		String filename = data.getFilename();
		filename=getStr(request, filename);
		if(file.exists()){
			 response.reset();
	         response.setContentType("application/x-msdownload");
	         response.addHeader("Content-Disposition", "attachment; filename=" + filename );//filename是默认的保存文件名
	         ServletOutputStream out = response.getOutputStream(); //得到响应输出流
	         byte[] buf=new byte[4096];//文件缓冲区
	         InputStream in=new FileInputStream(file); //要下载文件的输入流
	         int size; //每次从输入流读取的字节数
	         while((size=in.read(buf))!=-1){   //读
	        	 out.write(buf,0,size);  //写
	         }
	         in.close();  //关输入流
	         out.flush();
	         out.close();//关输出流
		}
		return null;
	}
	
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
	        String agent = request.getHeader("USER-AGENT");  
	         try {
	            	 if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
	            		 downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
	            	 }else{
	            		 downloadFileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
	            	 }
			} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
			}
	        return downloadFileName;
	}


}
